package autoorder.zsxmlv.service;

import autoorder.zsxmlv.mapper.AccountMapper;
import autoorder.zsxmlv.po.Account;
import autoorder.zsxmlv.util.ExcelUtil;
import common.zsxmlv.enums.ResultEnum;
import common.zsxmlv.utils.PropertiesUtil;
import common.zsxmlv.utils.Utils;
import common.zsxmlv.vo.Result;
import common.zsxmlv.vo.Table;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.rmi.CORBA.Util;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: ZSXM
 * @Description:
 * @Company: DingZheng
 * @Date: Create by 2018/6/2 11:39
 * @Version: 1.0
 * @Modify by:
 */
@Service
@Transactional
public class AccountService {

    @Resource
    private AccountMapper accountMapper;

    /**
     * insert account
     * @param account account object
     * @return return result object
     */
    public Result insert(Account account){
        Result result = new Result();
        if (account != null){
            Account account1 = accountMapper.selectByCustname(account.getCustname());
            if (account1 == null){
                int insert = accountMapper.insert(account);
                if (insert >= 1){
                    result.setSuccess(true);
                    result.setMsg(ResultEnum.INSERT_SUCCESS.getMsg());
                }else {
                    result.setSuccess(false);
                    result.setMsg(ResultEnum.INSERT_ERROR.getMsg());
                }
            }else{
                result.setSuccess(false);
                result.setMsg("该账号已存在,请勿重复添加");
            }
        }else{
            result.setSuccess(false);
            result.setMsg(ResultEnum.PARAM_ERROR.getMsg());
        }
        return result;
    }

    /**
     * delete account by id
     * @param id account id
     * @return result result object
     */
    public Result deleteById(Integer id) {
        Result result = new Result();
        if (id != null && id != 0){
            Account account = accountMapper.selectByPrimaryKey(id);
            if (account != null) {
                int i = accountMapper.deleteByPrimaryKey(id);
                if (i >= 1){
                    result.setSuccess(true);
                    result.setMsg(ResultEnum.DELETE_SUCCESS.getMsg());
                }else {
                    result.setSuccess(false);
                    result.setMsg(ResultEnum.DELETE_ERROR.getMsg());
                }
            }else{
                result.setSuccess(false);
                result.setMsg(ResultEnum.NOT_FOUND_DELETE_ERROR.getMsg());
            }
        }else {
            result.setSuccess(false);
            result.setMsg(ResultEnum.PARAM_ERROR.getMsg());
        }
        return result;
    }

    /**
     * select list by page
     * @param page pageNum
     * @param limit pageSize
     * @param username username
     * @param custname custname
     * @return layui table data
     */
    public Table getAccountListByPage(Integer page, Integer limit,String username, String custname,Integer disabled) {
        Table table = new Table();
        boolean condition = page != null && page != 0 && limit != null && limit != 0;
        if (condition){
            System.out.println(username);
            System.out.println(custname);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("startRecord", (page - 1) * limit);
            map.put("pageSize", limit);
            map.put("username", username);
            map.put("custname", custname);
            map.put("disabled", disabled);
            List<Account> accounts = accountMapper.selectByPage(map);
            int count = accountMapper.selectByCount(map);
            if (accounts.isEmpty()) {
                table.setCode(ResultEnum.NOT_FOUND.getCode());
                table.setMsg(ResultEnum.NOT_FOUND.getMsg());
            }else {
                table.setCount(count);
                table.setData(accounts);
                table.setMsg(ResultEnum.SUCCESS.getMsg());
                table.setCode(ResultEnum.SUCCESS.getCode());
            }
        }else {
            table.setMsg(ResultEnum.PARAM_ERROR.getMsg());
            table.setCode(ResultEnum.PARAM_ERROR.getCode());
        }
        return table;
    }

    /**
     * select account by id
     * @param id account id
     * @return return result object
     */
    public Result getAccountById(Integer id){
        Result result = new Result();
        boolean flag = false;
        if (id != null && id != 0){
            Account account = accountMapper.selectByPrimaryKey(id);
            if (account != null) {
                flag = true;
                result.setData(account);
            }else {
                result.setMsg(ResultEnum.NOT_FOUND.getMsg());
            }
        }else {
            result.setMsg(ResultEnum.PARAM_ERROR.getMsg());
        }
        result.setSuccess(flag);
        return result;
    }

    /**
     * 获取单个对象
     * @param id
     * @return
     */
    public Account getById(Integer id) {
        return accountMapper.selectByPrimaryKey(id);
    }

    /**
     * update account status by id
     * @param id account id
     * @return return result object
     */
    public Result updateStatus(Integer id){
        Result result = new Result();
        if (id != null && id != 0){
            Account account = accountMapper.selectByPrimaryKey(id);
            if (account != null) {
                Integer disabled = account.getDisabled();
                String msg = "";
                if (disabled == 1){
                    disabled = 0;
                    msg = "启用成功";
                }else{
                    disabled = 1;
                    msg = "停用成功";
                }
                account.setDisabled(disabled);
                int i = accountMapper.updateByPrimaryKey(account);
                if (i>=1){
                    result.setSuccess(true);
                    result.setMsg(msg);
                }else {
                    result.setSuccess(false);
                    result.setMsg(msg);
                }
            }else {
                result.setSuccess(false);
                result.setMsg(ResultEnum.NOT_FOUND_UPDATE_ERROR.getMsg());
            }
        }else {
            result.setSuccess(false);
            result.setMsg(ResultEnum.PARAM_ERROR.getMsg());
        }
        return result;
    }

    /**
     * update account by id
     * @param account account
     * @return return result object
     */
    public Result updateAccountById(Account account){
        Result result = new Result();
        if (account != null && account.getId() != 0){
            Account a = accountMapper.selectByPrimaryKey(account.getId());
            if (a != null) {
                int i = accountMapper.updateByPrimaryKeySelective(account);
                if (i>=1){
                    result.setSuccess(true);
                    result.setMsg(ResultEnum.UPDATE_SUCCESS.getMsg());
                }else {
                    result.setSuccess(false);
                    result.setMsg(ResultEnum.UPDATE_ERROR.getMsg());
                }
            }else {
                result.setSuccess(false);
                result.setMsg(ResultEnum.NOT_FOUND_UPDATE_ERROR.getMsg());
            }
        }else {
            result.setSuccess(false);
            result.setMsg(ResultEnum.PARAM_ERROR.getMsg());
        }
        return result;
    }


    /**
     * 根据状态获取所有账号
     * @param disabled 是否禁用
     * @return
     */
    public List<Account> listAllByStatus(Integer disabled) {
        return accountMapper.listAllByStatus(disabled);
    }

    /**
     * 批量删除账号
     * @param ids 需要删除的ID集合
     * @return result信息
     */
    public Result batchDeleteByIds(String ids) {
        Result result = new Result();
        if (!"".equals(ids)) {
            String[] split = ids.split(",");
            int[] ints = Utils.stringToInt(split);
            accountMapper.batchDeleteByIds(ints);
            result.setSuccess(true);
            result.setMsg("删除成功");
        } else {
            result.setSuccess(false);
            result.setMsg("请选择您需要删除的账号！");
        }
        return result;
    }

    /**
     * 批量导入账号
     * @param file
     * @return
     */
    public Result uploadFile(CommonsMultipartFile file) {
        Result result = new Result();
        try {
            long start = System.currentTimeMillis();
            String path = PropertiesUtil.getValue("auto_order.properties", "uploadUrl");
            String fileName = new String(file.getOriginalFilename().getBytes("ISO8859-1"), "UTF-8");
            fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + fileName;
            String filePath = path + fileName;

            //获取输出流
            OutputStream os=new FileOutputStream(filePath);
            //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
            InputStream is=file.getInputStream();
            int temp;
            //一个一个字节的读取并写入
            while((temp=is.read())!=(-1))
            {
                os.write(temp);
            }
            os.flush();
            os.close();
            is.close();
            List<Account> excelData = ExcelUtil.getExcelData(filePath);
            int i = accountMapper.insertByBatch(excelData);
            if (i > 0) {
                result.setSuccess(true);
                result.setMsg("上传成功");
            } else {
                result.setSuccess(false);
                result.setMsg("上传失败");
            }
            long end = System.currentTimeMillis();
            System.out.println("耗时：" + (end - start)/1000 + "秒");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
